import * as THREE from 'three';
import { TransformControls } from 'three/addons/controls/TransformControls.js';

/**
 * Transform Controls 管理器
 * 负责管理场景中的变换控制器（位置、旋转、缩放）
 */
export class TransformControlsManager {
    constructor(scene, camera, renderer, cameraController) {
        this.scene = scene;
        this.camera = camera;
        this.renderer = renderer;
        this.cameraController = cameraController; // 需要在拖拽时禁用相机控制
        
        this.transformControls = null;
        this.currentObject = null; // 当前附加的3D对象
        this.currentNode = null; // 当前选中的节点数据
        this.mode = 'translate'; // 'translate', 'rotate', 'scale'
        this.enabled = true;
        
        // 🔧 记录移动前的位置信息
        this.transformBeforeDrag = {
            position: null,
            rotation: null,
            scale: null
        };
        
        this.callbacks = {
            onChange: null, // Transform变化时的回调
            onDraggingChanged: null // 拖拽状态变化的回调
        };
        
        this.init();
    }
    
    init() {
        // 创建 TransformControls
        this.transformControls = new TransformControls(
            this.camera,
            this.renderer.domElement
        );
        
        // 设置模式
        this.transformControls.setMode(this.mode);
        
        // 设置大小
        this.transformControls.setSize(0.8);
        
        // 添加到场景
        this.scene.add(this.transformControls);
        
        // 监听拖拽事件
        this.transformControls.addEventListener('dragging-changed', (event) => {
            const isDragging = event.value;
            
            // 拖拽时禁用相机控制
            if (this.cameraController) {
                this.cameraController.enabled = !isDragging;
            }
            
            // 🔧 记录移动前后的位置
            if (this.currentObject) {
                const objName = this.currentObject.name || '(unnamed)';
                const objType = this.currentObject.type;
                
                if (isDragging) {
                    // 开始拖拽：记录初始位置
                    this.transformBeforeDrag.position = this.currentObject.position.clone();
                    this.transformBeforeDrag.rotation = this.currentObject.rotation.clone();
                    this.transformBeforeDrag.scale = this.currentObject.scale.clone();
                    
                    // 记录世界坐标
                    const worldPos = new THREE.Vector3();
                    this.currentObject.getWorldPosition(worldPos);
                    this.transformBeforeDrag.worldPosition = worldPos.clone();
                    
                    const actionName = this.mode === 'translate' ? '移动' : this.mode === 'rotate' ? '旋转' : '缩放';
                    console.log(`🎯 [开始${actionName}${objType}] "${objName}"`);
                } else {
                    // 结束拖拽
                    const worldPosAfter = new THREE.Vector3();
                    this.currentObject.getWorldPosition(worldPosAfter);
                    
                    const worldPosDelta = new THREE.Vector3().subVectors(worldPosAfter, this.transformBeforeDrag.worldPosition);
                    
                    console.log(`✅ [完成${this.mode === 'translate' ? '移动' : this.mode === 'rotate' ? '旋转' : '缩放'}${objType}] "${objName}"`);
                    console.log(`   📏 变化: ${worldPosDelta.length().toFixed(3)}m`);
                }
            }
            
            // 触发回调
            if (this.callbacks.onDraggingChanged) {
                this.callbacks.onDraggingChanged(isDragging);
            }
        });
        
        // 监听变换事件
        this.transformControls.addEventListener('change', () => {
            // 触发回调，通知外部更新节点数据
            if (this.callbacks.onChange && this.currentObject && this.currentNode) {
                this.callbacks.onChange(this.currentNode, this.currentObject);
            }
        });
        
        // 监听鼠标事件，用于拖拽结束后保存数据
        this.transformControls.addEventListener('mouseUp', () => {
            if (this.callbacks.onMouseUp && this.currentNode && this.currentObject) {
                this.callbacks.onMouseUp(this.currentNode, this.currentObject);
            }
        });
    }
    
    /**
     * 附加到指定的3D对象
     * @param {THREE.Object3D} object - 要控制的3D对象
     * @param {Object} node - 对应的节点数据
     */
    attach(object, node) {
        if (!object) {
            console.warn('⚠️ 无法附加 Transform Controls: 对象为空');
            return;
        }
        this.currentObject = object;
        this.currentNode = node;
        this.transformControls.attach(object);
        this.show();
    }
    
    /**
     * 分离当前对象
     */
    detach() {
        this.transformControls.detach();
        this.currentObject = null;
        this.currentNode = null;
        
        // 清空移动前的位置记录
        this.transformBeforeDrag = {
            position: null,
            rotation: null,
            scale: null,
            worldPosition: null
        };
        
        this.hide();
    }
    
    /**
     * 设置变换模式
     * @param {string} mode - 'translate', 'rotate', 'scale'
     */
    setMode(mode) {
        if (!['translate', 'rotate', 'scale'].includes(mode)) {
            console.warn(`⚠️ 无效的 Transform 模式: ${mode}`);
            return;
        }
        
        this.mode = mode;
        this.transformControls.setMode(mode);
    }
    
    /**
     * 获取当前模式
     */
    getMode() {
        return this.mode;
    }
    
    /**
     * 显示控制器
     */
    show() {
        this.transformControls.visible = true;
        this.enabled = true;
    }
    
    /**
     * 隐藏控制器
     */
    hide() {
        this.transformControls.visible = false;
        this.enabled = false;
    }
    
    /**
     * 启用/禁用控制器
     */
    setEnabled(enabled) {
        this.enabled = enabled;
        this.transformControls.enabled = enabled;
    }
    
    /**
     * 设置变化回调
     * @param {Function} callback - (node, object) => {}
     */
    onChange(callback) {
        this.callbacks.onChange = callback;
    }
    
    /**
     * 设置拖拽状态变化回调
     * @param {Function} callback - (isDragging) => {}
     */
    onDraggingChanged(callback) {
        this.callbacks.onDraggingChanged = callback;
    }
    
    /**
     * 设置鼠标释放回调
     * @param {Function} callback - (node, object) => {}
     */
    onMouseUp(callback) {
        this.callbacks.onMouseUp = callback;
    }
    
    /**
     * 销毁控制器
     */
    dispose() {
        if (this.transformControls) {
            this.transformControls.detach();
            this.transformControls.dispose();
            this.scene.remove(this.transformControls);
            this.transformControls = null;
        }
        
        this.currentObject = null;
        this.currentNode = null;
        this.callbacks = {};
    }
}

